Receiving Arguments from the Command line

Receving arguments from the command line is possible via an inbuilt module in Python called 'sys'. This module provides access to variables used or maintained by the interpreter. Read more about the 'sys' module in the Python documentation

Hands On

There is a python script in this folder called sys_arg.py. Now run the script from the command line passing a value along with it. Do it like this 'python sys_arg.py glow'

Result

When you run that command you are meant to get a list containing some parameters. The first value is the name of the script we are running and the second value is the argument you passed along with the script.

Explanation


In [ ]:
import sys # means we are telling Python that we need everything about sys in this script

Importing 'sys' makes all the properties and methods defined inside of 'sys' avalable for our use. 'Sys' is like a file containing properties and methods. Anything thing we use the import on is called a module

Without this line in the script we would not be able to run the code below.

CURIOUS?

Remove the import line in the script and then run the script from the command line. When you do this you are meant to get an error

Read More

imports and modules

Later on we would be creating out own module


In [ ]:
print sys.argv

argv is a method(function) defined inside of 'sys'. As we now know what is does, it returns a list of arguments passed to the script from the command line.

Since we know that we will get a list as a result, this means that we can apply all the methods that apply to list data types to the method
For example:

In [ ]:
print sys.argv[1:]

This would give you a list excluding the first item from the former code. if you do not understand all this try comparing


In [ ]:
print sys.argv

and


In [ ]:
print sys.argv[1:]

---- What is the difference in the results from the two codes? -----

Practice

  1. Create a file and give it any name you want (make sure it is a python file)
  2. Make the file print out all the arguments passed to it from the command line
  3. Run the script from the command line passing to it 5 arguments from the command line
Disclaimer

For any errors pls contact the Group

Next

Creating Modules


In [ ]: